package com.ytclub.auth.domain.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.ytclub.auth.common.enums.AuthPermissionShowEnum;
import com.ytclub.auth.common.enums.AuthPermissionStatusEnum;
import com.ytclub.auth.common.enums.IsDeletedFlagEnum;
import com.ytclub.auth.domain.constants.AuthConstant;
import com.ytclub.auth.domain.convent.AuthPermissionBOConverter;
import com.ytclub.auth.domain.entity.AuthPermissionBO;
import com.ytclub.auth.domain.redis.RedisUtil;
import com.ytclub.auth.domain.service.AuthPermissionDoaminService;
import com.ytclub.auth.infra.basic.entity.AuthPermission;
import com.ytclub.auth.infra.basic.entity.AuthRole;
import com.ytclub.auth.infra.basic.entity.AuthUser;
import com.ytclub.auth.infra.basic.entity.AuthUserRole;
import com.ytclub.auth.infra.basic.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 权限领域层接口实现类
 *
 * @author: HuangQi
 * @date: Created in 21:14 2023/12/19
 * @description: 权限领域层接口实现类
 */
@Service
@Slf4j
public class AuthPermissionDoaminServiceImpl implements AuthPermissionDoaminService {

    @Resource
    private AuthUserService authUserService;

    @Resource
    private AuthRoleService authRoleService;

    @Resource
    private AuthUserRoleService authUserRoleService;

    @Resource
    private AuthRolePermissionService authRolePermissionService;

    @Resource
    private AuthPermissionService authPermissionService;

    @Resource
    private RedisUtil redisUtil;


    /**
     * 新增角色
     *
     * @param authPermissionBO 新增角色的信息
     * @return 新增结果
     */
    @Override
    public Boolean add(AuthPermissionBO authPermissionBO) {
        if (log.isInfoEnabled()) {
            log.info("AuthPermissionDoaminServiceImpl.add.bo:{}", JSON.toJSONString(authPermissionBO));
        }

        // 参数转换
        AuthPermission authPermission = AuthPermissionBOConverter.INSTANCE.convertBoToEntity(authPermissionBO);
        authPermission.setStatus(AuthPermissionStatusEnum.OPEN.getCode());
        authPermission.setShow(AuthPermissionShowEnum.UN_SHOW.getCode());
        authPermission.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());

        // 调用service
        Integer count = authPermissionService.insert(authPermission);

        // 返回结果
        return count > 0;
    }


    /**
     * 更新权限
     *
     * @param authPermissionBO 更新权限的信息
     * @return 更新结果
     */
    @Override
    public Boolean update(AuthPermissionBO authPermissionBO) {
        if (log.isInfoEnabled()) {
            log.info("AuthPermissionDoaminServiceImpl.update.bo:{}", JSON.toJSONString(authPermissionBO));
        }

        // 参数转换
        AuthPermission authPermission = AuthPermissionBOConverter.INSTANCE.convertBoToEntity(authPermissionBO);

        // 调用service
        Integer count = authPermissionService.update(authPermission);

        // 返回结果
        return count > 0;
    }

    /**
     * 删除权限(逻辑删除)
     *
     * @param authPermissionBO 删除权限的信息
     * @return 删除结果
     */
    @Override
    public Boolean delete(AuthPermissionBO authPermissionBO) {
        if (log.isInfoEnabled()) {
            log.info("AuthPermissionDoaminServiceImpl.delete.bo:{}", JSON.toJSONString(authPermissionBO));
        }

        // 参数转换
        AuthPermission authPermission = AuthPermissionBOConverter.INSTANCE.convertBoToEntity(authPermissionBO);
        authPermission.setIsDeleted(IsDeletedFlagEnum.DELETED.getCode());

        // 调用service
        Integer count = authPermissionService.update(authPermission);

        // 返回结果
        return count > 0;
    }

    /**
     * 获取用户权限
     *
     * @param userName 用户名
     * @return 用户权限
     */
    @Override
    public List<String> getPermission(String userName) {
        log.info("AuthPermissionDoaminServiceImpl.getPermission.userName:{}", userName);

        // 构建redis查询key
        String permissionKey = redisUtil.buildKey(AuthConstant.AUTH_PERMISSION_PREFIX, userName);
        String permissionValue = redisUtil.get(permissionKey);
        List<String> authList = new LinkedList<>();
        if (StringUtils.isBlank(permissionValue)) {
            // 如果从redis中拿到的value为空,查询数据库
            // 拿到用户id
            Long id = authUserService.queryByUserName(userName).getId();

            // 根据用户id查询角色id列表
            List<Long> roleIdList = authUserRoleService.queryByUserId(id);
            // 根据角色id列表查询角色信息
            List<AuthRole> roleList = authRoleService.queryByRoleList(roleIdList);
            // 将角色信息存入redis
            String roleKey = redisUtil.buildKey(AuthConstant.AUTH_ROLE_PREFIX, userName);
            redisUtil.set(roleKey, new Gson().toJson(roleList));

            // 通过角色id列表查询权限id列表
            List<Long> permissionIdList = authRolePermissionService.queryByRoleIdList(roleIdList);
            // 通过权限id列表查询权限信息
            List<AuthPermission> permissionList = authPermissionService.queryByPermisionIdList(permissionIdList);
            redisUtil.set(permissionKey, new Gson().toJson(permissionList));
            return Collections.emptyList();
        }
        // 如果从redis中拿到了value,将json字符串转换为AuthPermissionList
        List<AuthPermission> permissionList = new Gson().fromJson(permissionValue,
                new TypeToken<List<AuthPermission>>() {
                }.getType());
        // 将AuthPermissionList转换为stringList
        authList = permissionList.stream().map(AuthPermission::getPermissionKey).collect(Collectors.toList());

        // 返回结果
        return authList;
    }


}
